<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >库存管理(财务)</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >财务库存管理</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: toUrl }">{{
          pathName
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>
          编辑<span class="ccui-curr-crumb" :style="{ paddingLeft: '10px' }">{{
            this.storageName
          }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <basicInformation
              ref="formDateBUI"
              :storageList="finStorageList"
              :storageForm="storageForm"
              @updataForm="updataForm"
              @updataList="updataList"
            ></basicInformation>
          </el-tab-pane>
          <el-tab-pane label="采购清单" name="second">
            <contractList
              ref="contractList"
              :storage-list="finStorageList"
              :priceFillingMethodType="priceFillingMethodType"
              :editPcConId="editPcConId"
              :storageForm="storageForm"
              @delectList="delectList"
            ></contractList>
          </el-tab-pane>
          <el-tab-pane label="附件" name="third">
            <!-- <attachment ref="attachment"></attachment> -->
            <upload-info
              v-if="isTrue"
              ref="contractAppendix"
              isTab
              v-model="fileList"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <!-- <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" /> -->
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="saveStorage"
            >暂存</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-export"
            @click="submitHandle('submit')"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="resetHandle"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInformation from "./edit/basicInformation";
// import attachment from "./edit/attachment";
import UploadInfo from "@/basa/components/public/uploadInfo2";
import contractList from "./edit/contractList";
import BigNumber from "bignumber.js";
import {
  //getContractChanges
  getFinStorageById,
  saveFinStorage,
  submitFinStorage,
  tsSaveFinStorage
} from "../api/edit-item";
import { ishasAgentId } from "@/basa/utils";
import peopleManage from "../mixins/peopleManage";
// import { savePcConcSubProtocol } from "../../api/contractChange";
// import contractChangeMixins from "@/app/subContractManage/subcontractChange/mixins/contractChangeMixins";
export default {
  name: "edit-item",
  mixins: [peopleManage],
  components: {
    basicInformation,
    // attachment,
    UploadInfo,
    contractList
  },
  data() {
    return {
      isTrue: false,
      storageForm: {
        id: 0,
        count: "",
        storageCode: "",
        settlementCount: "",
        moneyWithTax: "",
        storageFormTolal: {}
      },
      storageName: "", // 入库单名称
      finStorageList: [],
      activeName: "first",
      submitFlag: false,
      priceFillingMethodType: "",
      taxRate: 0,
      focus: "formDateBUI",
      fileList: [], // 附件上传集合
      editPcConId: "",
      BillData: [], //总数组2
      contractListBool: false, //校验变更列表是否为空
      messageCount: ''
    };
  },
  watch: {
    $route(to, form) {
      if (to.name == "inventoryManagement-financeWarehousing-edit-item") {
        this.getFinStorageById();
      }
    }
  },
  created() {
    this.getFinStorageById();
  },
  activated() {
    this.activeName = "first";
  },
  methods: {
    updataList(val) {
      this.finStorageList = val;
    },
    updataForm(val) {
      this.storageForm.storageFormTolal = val;
    },
    delectList(val) {
      this.finStorageList = val.filter(item => item.check != true);
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    // 暂存
    saveStorage() {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId || row.fileInfoId;
        row.uploadTime = row.uploadTime ? row.uploadTime : row.createTime;
      });
      this.finStorageList.forEach((item, index) => {
        item.sn = ++index;
        item.createTime = new Date(item.createTime).getTime();
      });
      let obj = {
        finStorage: this.$refs.formDateBUI.form,
        files: fileList1,
        finStorageList: this.finStorageList
      };

      var currSetCount = 0;
      var currSetMoney = 0;
      for (var i = 0; i < this.finStorageList.length; i++) {
        if (this.finStorageList[i].settlementCount) {
          currSetCount += Number(this.finStorageList[i].settlementCount + "");
        }
        currSetMoney += Number(this.finStorageList[i].moneyWithTax + "");
      }
      obj.finStorage.currSetCount = currSetCount;
      obj.finStorage.currSetMoney = currSetMoney;
      // obj.finStorage.reportTime = new Date(obj.finStorage.reportTime).getTime();
      this.$loading({
        lock: true,
        text: "暂存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      tsSaveFinStorage(obj)
        .then(res => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "暂存成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          this.$loading().close();
        });
    },
    // 保存 提交
    submitHandle(name) {
      this.getValidate(this.finStorageList)
      this.$refs.formDateBUI.$refs.form.validate(valid => {
        if (valid) {
          if (this.contractListBool) {
              // 调接口
              if (name == "save") {
                this.saveFinStorage(name);
              } else {
                this.submitFinStorage(name);
              }
          } else {
            // 弹个窗
            this.$message({
              type: "error",
              message: this.messageCount,
              showClose: true,
              ccuiCustom: true
            });
          }
        } else {
          this.$showErrorMessage("入库单基本信息不完整，请编辑后保存");
          this.activeName = "first";
        }
      });
    },
    // edit详情
    getFinStorageById() {
      let obj = {
        ids: [this.$route.params.id]
      };
      getFinStorageById(obj).then(res => {
        res.data.data.finStorage.approvalAdoptTime = res.data.data.finStorage
          .approvalAdoptTime
          ? res.data.data.finStorage.approvalAdoptTime.substr(0, 10)
          : "";
        this.storageName = res.data.data.finStorage.storageName;
        res.data.data.finStorage.storageCount = (+res.data.data.finStorage.storageCount).toFixed(3);
        this.storageForm.count = res.data.data.finStorage.storageCount;
        this.storageForm.id = res.data.data.finStorage.id;
        this.storageForm.storageCode = res.data.data.finStorage.storageCode;
        this.storageForm.storageFormTolal = res.data.data.finStorage;
        this.$refs.formDateBUI.form = res.data.data.finStorage;
        res.data.data.finStorageList.forEach(item => {
          if ((+item.isOtherCost) == 1 || (+item.isServices) == 1) {
            if (item.relationList && item.relationList.length > 0) {
              let newList = [];
              item.relationList.forEach(val => {
                // val.pkPurmatdetl = val.id;
                val.storageCount = (+val.storageCount).toFixed(3);
                newList.push(val.storageCode);
              });
              item.relationCode = newList.join(",");
            }
          }
          if ((+item.isOtherCost) == 0 && (+item.isServices) == 0) {
            item.unStorageCount = (+item.remainStorageCount).toFixed(3);
            item.settlementCount = (+item.settlementCount).toFixed(3);
            item.storageCount = (+item.storageCount).toFixed(3);
            item.count = item.unStorageCount;
          }
          item.unitPriceWithTax = (+item.unitPriceWithTax).toFixed(2);
          if ((+item.isOtherCost) == 1 || (+item.isServices) == 1) {
            item.storageCount = "";
            item.unStorageCount =  "";
            item.unitPriceWithTax = "";
          } else {
            item.moneyWithTax = new BigNumber(
              Number(item.unitPriceWithTax)
            ).multipliedBy(Number(item.storageCount));
          }

          item.moneyWithTax = (+item.moneyWithTax).toFixed(2);
          // item.moneyWithoutTax = item.moneyWithTax / (1 + Number(item.taxRate));
          let taxRate = new BigNumber(Number(item.taxRate)).plus(1).toString();
          item.moneyWithoutTax = item.moneyWithTax
            ? new BigNumber(Number(item.moneyWithTax)).dividedBy(taxRate)
            : "";
          item.moneyWithoutTax = (+item.moneyWithoutTax).toFixed(2);
        });

        this.finStorageList = res.data.data.finStorageList;

        this.fileList = res.data.data.files;
        this.isTrue = true;
      });
    },
    // 保存/提交
    saveFinStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId || row.fileInfoId;
        row.uploadTime = row.uploadTime ? row.uploadTime : row.createTime;
      });
      this.finStorageList.forEach((item, index) => {
        item.sn = ++index;
        item.createTime = new Date(item.createTime).getTime();
      });
      let obj = {
        finStorage: this.$refs.formDateBUI.form,
        files: fileList1,
        finStorageList: this.finStorageList
      };

      var currSetCount = 0;
      var currSetMoney = 0;
      for (var i = 0; i < this.finStorageList.length; i++) {
        if (this.finStorageList[i].settlementCount) {
          currSetCount += Number(this.finStorageList[i].settlementCount + "");
        }
        currSetMoney += Number(this.finStorageList[i].moneyWithTax + "");
      }
      obj.finStorage.currSetCount = currSetCount;
      obj.finStorage.currSetMoney = currSetMoney;

      this.$loading({
        lock: true,
        text: "保存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      saveFinStorage(obj)
        .then(res => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "保存并校验成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          this.$loading().close();
        });
    },
    submitFinStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId || row.fileInfoId;
        row.uploadTime = row.uploadTime ? row.uploadTime : row.createTime;
      });
      this.finStorageList.forEach((item, index) => {
        item.sn = ++index;
        item.createTime = new Date(item.createTime).getTime();
      });
      let obj = {
        finStorage: this.$refs.formDateBUI.form,
        files: fileList1,
        finStorageList: this.finStorageList
      };

      var currSetCount = 0;
      var currSetMoney = 0;
      for (var i = 0; i < this.finStorageList.length; i++) {
        if (this.finStorageList[i].settlementCount) {
          currSetCount += Number(this.finStorageList[i].settlementCount + "");
        }
        currSetMoney += Number(this.finStorageList[i].moneyWithTax + "");
      }
      obj.finStorage.currSetCount = currSetCount;
      obj.finStorage.currSetMoney = currSetMoney;

      this.$loading({
        lock: true,
        text: "提交中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      submitFinStorage(obj)
        .then(res => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "保存并提交成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          this.$loading().close();
        });
    },
    // 校验变更列表不能为空
    getValidate(data) {
      let newArr = data.filter(item => item.relationList);
      let newArrTow = [];
      newArr.forEach(item => {
        if(item.isOtherCost == 1 || item.isServices == 1) {
          newArrTow.push(item);
        }
      })
      let a = [];
      newArrTow.forEach(item => {
        if(item.materialCode == '') {
          return a.push(item.materialName);
        } else if(item.materialCode && item.materialCode != '') {
          return this.messageCount = "设备物资编码" + item.materialCode + ",请关联入库单"
        }
      })
      if(a.length > 0) {
        this.messageCount = a.join(",请关联入库单; ") + ",请关联入库单;"
      }
      this.contractListBool = newArrTow.every(item => {
        return item.relationList.length;
      })
    },
    // 取消
    resetHandle() {
      this.handleBack();
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/contracts/contractChangeEntry/un-submitted"
      );
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style lang="scss" scoped>
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}

// 表格固定滚动条划不动的解决样式
// /deep/ .el-table__body-wrapper {
//   z-index: 1;
// }
/deep/ .el-tabs__customize {
    padding-bottom: 50px;
}
</style>
